package com.atguigu.servlet;

import com.atguigu.domain.Book;
import com.atguigu.domain.Page;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

/**
 * @author dl
 * @date 2020/4/29 12:49
 */
@WebServlet(name = "IndexServlet",urlPatterns = "/index")
public class IndexServlet extends BaseServlet {

    // todo 暂时 因为首页也还是去查找图书  所以这里直接可以使用 BookService 中的 getPage 方法
    private BookService bookService = new BookServiceImpl();

    /**
     * 首页分页方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @deprecated 因为首页的page方法需要带上根据价格查询区间 所以这个方法不再适合
     */
    @Deprecated
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String currentPage = req.getParameter("current_page");
        Page<Book> page = bookService.getPage(currentPage, "4");
        req.setAttribute("list",page);
        // 将请求转发到 forward.jsp
        page.setUrl("/index?method=page&current_page=");
        req.getRequestDispatcher("/forword.jsp").forward(req,resp);
    }

    @Deprecated
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String currentPage = req.getParameter("current_page");
        String minPrice = req.getParameter("min_price");
        String maxPrice = req.getParameter("max_price");
        Optional<String> optionalMin = Optional.ofNullable(minPrice);
        String min = optionalMin.orElse("");
        Optional<String> optionalMax = Optional.ofNullable(maxPrice);
        String max = optionalMax.orElse("");
        Page<Book> page = bookService.getPageByPrice(currentPage, "4",minPrice,maxPrice);
        req.setAttribute("list",page);
        // 将请求转发到 forward.jsp
        page.setUrl("/index?method=pageByPrice&min_price="+min+"&max_price="+max+"&current_page=");
        req.getRequestDispatcher("/forword.jsp").forward(req,resp);
    }





}
